package com.kexilo.system.user.service;

import com.kexilo.core.common.annotation.DataScope;
import com.kexilo.core.common.exception.ServiceException;
import com.kexilo.core.common.utils.SecurityUtils;
import com.kexilo.core.common.utils.StringUtils;
import com.kexilo.core.role.domain.SysRole;
import com.kexilo.core.role.domain.SysUserRole;
import com.kexilo.core.user.domain.SysUser;
import com.kexilo.core.security.dto.UserDTO;
import com.kexilo.core.security.service.IUserService;
import com.kexilo.system.user.mapper.SysRoleMapper;
import com.kexilo.system.user.mapper.SysUserMapper;
import com.kexilo.system.user.mapper.SysUserRoleMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.Set;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 用户 业务层处理
 * 
 * @author Kexilo
 */
@Service
public class SysUserServiceImpl implements ISysUserService, IUserService {
    
    private static final Logger log = LoggerFactory.getLogger(SysUserServiceImpl.class);

    @Autowired
    private SysUserMapper userMapper;

    @Autowired
    private SysRoleMapper roleMapper;

    @Autowired
    private SysUserRoleMapper userRoleMapper;

    /**
     * 根据条件分页查询用户列表
     * 
     * @param user 用户信息
     * @return 用户信息集合信息
     */
    @Override
    @DataScope(deptAlias = "d", userAlias = "u")
    public List<SysUser> selectUserList(SysUser user) {
        return userMapper.selectUserList(user);
    }

    /**
     * 根据条件分页查询已分配用户角色列表
     * 
     * @param user 用户信息
     * @return 用户信息集合信息
     */
    @Override
    public List<SysUser> selectAllocatedList(SysUser user) {
        return userMapper.selectAllocatedList(user);
    }

    /**
     * 根据条件分页查询未分配用户角色列表
     * 
     * @param user 用户信息
     * @return 用户信息集合信息
     */
    @Override
    public List<SysUser> selectUnallocatedList(SysUser user) {
        return userMapper.selectUnallocatedList(user);
    }

    /**
     * 通过用户名查询用户
     * 
     * @param username 用户名
     * @return 用户对象信息
     */
    @Override
    @Cacheable(value = "user:info", key = "#username", condition = "#username != null")
    public SysUser selectUserByUserName(String username) {
        return userMapper.selectUserByUserName(username);
    }

    /**
     * 通过用户ID查询用户
     * 
     * @param userId 用户ID
     * @return 用户对象信息
     */
    @Override
    @Cacheable(value = "user:info", key = "#userId", condition = "#userId != null && #userId > 0")
    public SysUser selectUserById(Long userId) {
        return userMapper.selectUserById(userId);
    }

    /**
     * 查询用户所属角色组
     * 
     * @param username 用户名
     * @return 结果
     */
    @Override
    @Cacheable(value = "user:roles", key = "#username", condition = "#username != null")
    public String selectUserRoleGroup(String username) {
        List<SysRole> list = roleMapper.selectRolesByUserName(username);
        if (CollectionUtils.isEmpty(list)) {
            return StringUtils.EMPTY;
        }
        return list.stream().map(SysRole::getRoleName).collect(Collectors.joining(","));
    }

    /**
     * 查询用户所属岗位组
     * 
     * @param username 用户名
     * @return 结果
     */
    @Override
    public String selectUserPostGroup(String username) {
        try {
            // 注意：这里需要岗位相关的Mapper和实体，当前作为基础实现
            // 实际项目中需要创建SysPost实体和SysPostMapper
            
            // 临时实现：模拟岗位查询
            if (StringUtils.isEmpty(username)) {
                return StringUtils.EMPTY;
            }
            
            // 根据用户名查询用户信息
            SysUser user = userMapper.selectUserByUserName(username);
            if (user == null) {
                return StringUtils.EMPTY;
            }
            
            // 模拟岗位数据（实际应从数据库查询）
            if ("admin".equals(username)) {
                return "系统管理员";
            } else {
                return "普通用户";
            }
            
        } catch (Exception e) {
            log.error("查询用户岗位异常: username={}, error={}", username, e.getMessage(), e);
            return StringUtils.EMPTY;
        }
    }

    /**
     * 校验用户名称是否唯一
     * 
     * @param user 用户信息
     * @return 结果
     */
    @Override
    public boolean checkUserNameUnique(SysUser user) {
        Long userId = StringUtils.isNull(user.getUserId()) ? -1L : user.getUserId();
        SysUser info = userMapper.checkUserNameUnique(user.getUsername());
        if (StringUtils.isNotNull(info) && info.getUserId().longValue() != userId.longValue()) {
            return false;
        }
        return true;
    }

    /**
     * 校验手机号码是否唯一
     *
     * @param user 用户信息
     * @return 结果
     */
    @Override
    public boolean checkPhoneUnique(SysUser user) {
        Long userId = StringUtils.isNull(user.getUserId()) ? -1L : user.getUserId();
        SysUser info = userMapper.checkPhoneUnique(user.getPhone());
        if (StringUtils.isNotNull(info) && info.getUserId().longValue() != userId.longValue()) {
            return false;
        }
        return true;
    }

    /**
     * 校验email是否唯一
     *
     * @param user 用户信息
     * @return 结果
     */
    @Override
    public boolean checkEmailUnique(SysUser user) {
        Long userId = StringUtils.isNull(user.getUserId()) ? -1L : user.getUserId();
        SysUser info = userMapper.checkEmailUnique(user.getEmail());
        if (StringUtils.isNotNull(info) && info.getUserId().longValue() != userId.longValue()) {
            return false;
        }
        return true;
    }

    /**
     * 校验用户是否允许操作
     * 
     * @param user 用户信息
     */
    @Override
    public void checkUserAllowed(SysUser user) {
        if (StringUtils.isNotNull(user.getUserId()) && user.isAdmin()) {
            throw new ServiceException("不允许操作超级管理员用户");
        }
    }

    /**
     * 校验用户是否有数据权限
     * 
     * @param userId 用户id
     */
    @Override
    public void checkUserDataScope(Long userId) {
        if (!SysUser.isAdmin(SecurityUtils.getUserId())) {
            SysUser user = new SysUser();
            user.setUserId(userId);
            List<SysUser> users = this.selectUserList(user);
            if (StringUtils.isEmpty(users)) {
                throw new ServiceException("没有权限访问用户数据！");
            }
        }
    }

    /**
     * 新增保存用户信息
     * 
     * @param user 用户信息
     * @return 结果
     */
    @Override
    @Transactional
    public int insertUser(SysUser user) {
        // 新增用户信息
        int rows = userMapper.insertUser(user);
        // 新增用户角色关联
        insertUserRole(user);
        return rows;
    }

    /**
     * 注册用户信息
     * 
     * @param user 用户信息
     * @return 结果
     */
    @Override
    public boolean registerUser(SysUser user) {
        user.setPassword(SecurityUtils.encryptPassword(user.getPassword()));
        return userMapper.insertUser(user) > 0;
    }

    /**
     * 修改保存用户信息
     * 
     * @param user 用户信息
     * @return 结果
     */
    @Override
    @Transactional
    @CacheEvict(value = {"user:info", "user:permissions", "user:roles"}, key = "#user.userId")
    public int updateUser(SysUser user) {
        Long userId = user.getUserId();
        // 删除用户与角色关联
        userRoleMapper.deleteUserRoleByUserId(userId);
        // 新增用户与角色管理
        insertUserRole(user);
        return userMapper.updateUser(user);
    }

    /**
     * 用户授权角色
     * 
     * @param userId 用户ID
     * @param roleIds 角色组
     */
    @Override
    @Transactional
    @CacheEvict(value = {"user:permissions", "user:roles"}, key = "#userId")
    public void insertUserAuth(Long userId, Long[] roleIds) {
        userRoleMapper.deleteUserRoleByUserId(userId);
        insertUserRole(userId, roleIds);
    }

    /**
     * 修改用户状态
     * 
     * @param user 用户信息
     * @return 结果
     */
    @Override
    public int updateUserStatus(SysUser user) {
        return userMapper.updateUser(user);
    }

    /**
     * 修改用户基本信息
     * 
     * @param user 用户信息
     * @return 结果
     */
    @Override
    public int updateUserProfile(SysUser user) {
        return userMapper.updateUser(user);
    }

    /**
     * 修改用户头像
     * 
     * @param username 用户名
     * @param avatar 头像地址
     * @return 结果
     */
    @Override
    public boolean updateUserAvatar(String username, String avatar) {
        return userMapper.updateUserAvatar(username, avatar) > 0;
    }

    /**
     * 重置用户密码
     * 
     * @param user 用户信息
     * @return 结果
     */
    @Override
    public int resetPwd(SysUser user) {
        user.setPassword(SecurityUtils.encryptPassword(user.getPassword()));
        return updateUserProfile(user);
    }

    /**
     * 重置用户密码
     * 
     * @param username 用户名
     * @param password 密码
     * @return 结果
     */
    @Override
    public int resetUserPwd(String username, String password) {
        return userMapper.resetUserPwd(username, SecurityUtils.encryptPassword(password));
    }

    /**
     * 新增用户角色信息
     * 
     * @param user 用户对象
     */
    public void insertUserRole(SysUser user) {
        this.insertUserRole(user.getUserId(), user.getRoleIds());
    }

    /**
     * 新增用户角色信息
     * 
     * @param userId 用户ID
     * @param roleIds 角色组
     */
    public void insertUserRole(Long userId, Long[] roleIds) {
        if (StringUtils.isNotEmpty(roleIds)) {
            // 新增用户与角色管理
            List<SysUserRole> list = new ArrayList<SysUserRole>(roleIds.length);
            for (Long roleId : roleIds) {
                SysUserRole ur = new SysUserRole();
                ur.setUserId(userId);
                ur.setRoleId(roleId);
                list.add(ur);
            }
            userRoleMapper.batchUserRole(list);
        }
    }

    /**
     * 通过用户ID删除用户
     * 
     * @param userId 用户ID
     * @return 结果
     */
    @Override
    @Transactional
    public int deleteUserById(Long userId) {
        // 删除用户与角色关联
        userRoleMapper.deleteUserRoleByUserId(userId);
        return userMapper.deleteUserById(userId);
    }

    /**
     * 批量删除用户信息
     * 
     * @param userIds 需要删除的用户ID
     * @return 结果
     */
    @Override
    @Transactional
    public int deleteUserByIds(Long[] userIds) {
        for (Long userId : userIds) {
            checkUserAllowed(new SysUser(userId));
            checkUserDataScope(userId);
        }
        // 删除用户与角色关联
        userRoleMapper.deleteUserRole(userIds);
        return userMapper.deleteUserByIds(userIds);
    }

    /**
     * 导入用户数据
     * 
     * @param userList 用户数据列表
     * @param isUpdateSupport 是否更新支持，如果已存在，则进行更新数据
     * @param operName 操作用户
     * @return 结果
     */
    @Override
    public String importUser(List<SysUser> userList, Boolean isUpdateSupport, String operName) {
        if (StringUtils.isNull(userList) || userList.size() == 0) {
            throw new ServiceException("导入用户数据不能为空！");
        }
        int successNum = 0;
        int failureNum = 0;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();
        String password = "123456"; // 默认密码
        for (SysUser user : userList) {
            try {
                // 验证是否存在这个用户
                SysUser u = userMapper.selectUserByUserName(user.getUsername());
                if (StringUtils.isNull(u)) {
                    // 设置默认值
                    user.setPassword(SecurityUtils.encryptPassword(password));
                    user.setCreateBy(operName);
                    this.insertUser(user);
                    successNum++;
                    successMsg.append("<br/>").append(successNum).append("、账号 ").append(user.getUsername()).append(" 导入成功");
                } else if (isUpdateSupport) {
                    user.setUserId(u.getUserId());
                    user.setUpdateBy(operName);
                    this.updateUser(user);
                    successNum++;
                    successMsg.append("<br/>").append(successNum).append("、账号 ").append(user.getUsername()).append(" 更新成功");
                } else {
                    failureNum++;
                    failureMsg.append("<br/>").append(failureNum).append("、账号 ").append(user.getUsername()).append(" 已存在");
                }
            } catch (Exception e) {
                failureNum++;
                String msg = "<br/>" + failureNum + "、账号 " + user.getUsername() + " 导入失败：";
                failureMsg.append(msg).append(e.getMessage());
                log.error(msg, e);
            }
        }
        if (failureNum > 0) {
            failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据格式不正确，错误如下：");
            throw new ServiceException(failureMsg.toString());
        } else {
            successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条，数据如下：");
        }
        return successMsg.toString();
    }
    
    /**
     * 根据用户ID查询用户权限
     * 
     * @param userId 用户ID
     * @return 权限集合
     */
    @Override
    @Cacheable(value = "user:permissions", key = "#userId", 
               condition = "#userId != null && #userId > 0",
               unless = "#result == null || #result.isEmpty()")
    public Set<String> getUserPermissions(Long userId) {
        try {
            // 查询用户的菜单权限
            List<String> permissionList = userMapper.selectMenuPermsByUserId(userId);
            
            Set<String> permissions = new HashSet<>();
            if (permissionList != null && !permissionList.isEmpty()) {
                // 过滤掉空权限
                for (String permission : permissionList) {
                    if (StringUtils.isNotEmpty(permission)) {
                        permissions.add(permission.trim());
                    }
                }
            }
            
            // 如果是管理员，给予所有权限
            if (userId != null && userId == 1L) {
                permissions.add("*:*:*");
            }
            
            // 如果权限为空，给予基础权限
            if (permissions.isEmpty()) {
                permissions.add("system:user:list");
                permissions.add("system:user:query");
            }
            
            return permissions;
            
        } catch (Exception e) {
            log.error("查询用户权限异常: userId={}, error={}", userId, e.getMessage(), e);
            // 异常情况下返回基础权限
            Set<String> defaultPermissions = new HashSet<>();
            defaultPermissions.add("system:user:list");
            defaultPermissions.add("system:user:query");
            return defaultPermissions;
        }
    }
    
    /**
     * 根据用户ID查询用户角色列表
     * 
     * @param userId 用户ID
     * @return 角色列表
     */
    @Override
    @Cacheable(value = "user:role:list", key = "#userId", 
               condition = "#userId != null && #userId > 0")
    public List<SysRole> getUserRoles(Long userId) {
        return roleMapper.selectRolesByUserId(userId);
    }
    
    // ========== 实现IUserService接口（用于认证） ==========
    
    /**
     * 通过用户名查询用户（IUserService接口实现）
     * 
     * @param userName 用户名
     * @return UserDTO
     */
    @Override
    public UserDTO selectUserDTOByUserName(String userName) {
        SysUser sysUser = userMapper.selectUserByUserName(userName);
        return convertToUserDTO(sysUser);
    }
    
    /**
     * 通过用户ID查询用户（IUserService接口实现）
     * 
     * @param userId 用户ID
     * @return UserDTO
     */
    @Override
    public UserDTO selectUserDTOById(Long userId) {
        SysUser sysUser = userMapper.selectUserById(userId);
        return convertToUserDTO(sysUser);
    }
    
    // getUserPermissions方法已经在上面实现了，直接继承
    
    /**
     * 将SysUser转换为UserDTO
     * 
     * @param sysUser 系统用户对象
     * @return 用户DTO
     */
    private UserDTO convertToUserDTO(SysUser sysUser) {
        if (sysUser == null) {
            return null;
        }
        
        UserDTO userDTO = new UserDTO();
        userDTO.setUserId(sysUser.getUserId());
        userDTO.setDeptId(sysUser.getDeptId());
        userDTO.setUserName(sysUser.getUsername());
        userDTO.setNickName(sysUser.getNickname());
        userDTO.setEmail(sysUser.getEmail());
        userDTO.setPhonenumber(sysUser.getPhone());
        userDTO.setSex(sysUser.getSex());
        userDTO.setAvatar(sysUser.getAvatar());
        userDTO.setPassword(sysUser.getPassword());
        userDTO.setStatus(sysUser.getStatus());
        userDTO.setDelFlag(sysUser.getDelFlag());
        userDTO.setCreateTime(sysUser.getCreateTime());
        userDTO.setUpdateTime(sysUser.getUpdateTime());
        
        return userDTO;
    }
}
